package net.synck.gcontacts.views;


import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;


import net.synck.gcontacts.editor.ContactEditorInput;
import net.synck.gcontacts.preferences.PreferenceConstants;
import net.synck.gcontacts.ui.ContactEditor;
import net.synck.gcontacts.ui.UserCredentialsDialog;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.part.*;
import org.eclipse.ui.progress.IProgressService;
import org.eclipse.ui.progress.IWorkbenchSiteProgressService;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.equinox.internal.security.ui.Activator;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.*;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.*;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.SWT;

import com.google.api.gbase.client.FeedURLFactory;
import com.google.api.gbase.client.GoogleBaseAttributeId;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.GoogleBaseFeed;
import com.google.api.gbase.client.GoogleBaseQuery;
import com.google.api.gbase.client.ItemTypeDescription;
import com.google.gdata.client.Query;
import com.google.gdata.client.Query.CustomParameter;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class GContactsView extends ViewPart {
	private TableViewer viewer;
	private Action refreshAction;
	
	private Action doubleClickAction;
	private Action filterNameAction;
	private ViewerFilter filterNameFilter;
			
	private ContactFeed resultFeed = null; 
	
	class NameSorter extends ViewerSorter {
		
	}

	/**
	 * The constructor.
	 */
	public GContactsView() {
	}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());
		
		viewer.setComparator( new ViewerComparator() {
			@Override
			public int compare(Viewer viewer, Object e1, Object e2) {
				if (e1 instanceof ContactEntry && e2 instanceof ContactEntry) {
					return ((ContactEntry)e1).getTitle().getPlainText().compareTo(					
							((ContactEntry)e2).getTitle().getPlainText()
					);
				}
				return super.compare(viewer, e1, e2);
			}
			
		});
		
		
		Table table = viewer.getTable();
		
		TableColumn column = new TableColumn(table, SWT.LEFT,0);		
		column.setText("Name");
		column.setWidth(200);
		table.setSortColumn(column);
		
		column = new TableColumn(table, SWT.LEFT,1);		
		column.setText("Email");
		column.setWidth(150);
		
		column = new TableColumn(table, SWT.LEFT,2);		
		column.setText("Phone");
		column.setWidth(150);

		table.setHeaderVisible(true);
		
		
		viewer.setInput(getViewSite());
		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "net.synck.gcontacts.viewer");
		
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
		makeFilters();
		contributeFilters();
		
		getSite().setSelectionProvider(viewer);
	}

	private void contributeFilters() {
		/*
		ViewerFilter filters[] = new ViewerFilter[] {
				filterNameFilter
		};		
		viewer.setFilters(filters);
		*/
		viewer.addFilter(filterNameFilter);
	}

	private void makeFilters() {
		filterNameFilter = new ViewerFilter() {

			@Override
			public boolean select(Viewer viewer, Object parentElement,
					Object element) {
				String title =
					((ContactEntry)element).getTitle().getPlainText();
				return (title != null && !title.isEmpty());
			}
			
		};
		
		
	}

	private void connectGContacts() {		
		
		
		
		ContactsService myService = net.synck.gcontacts.Activator.getDefault()
			.getContactsService();
		
		  	  	
		try {
			URL feedUrl = new URL("http://www.google.com/m8/feeds/contacts/rachinsky@gmail.com/full");
			 Query myQuery = new Query(feedUrl);
			 myQuery.setMaxResults(Integer.MAX_VALUE);
			 myQuery.addCustomParameter( new CustomParameter("showdeleted", "true"));
			 resultFeed = myService.query(myQuery, ContactFeed.class);
			//resultFeed = myService.getFeed(feedUrl, ContactFeed.class);			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		/*
		IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
		try {
			progressService.runInUI(
				      PlatformUI.getWorkbench().getProgressService(),
				      new IRunnableWithProgress() {
				         public void run(IProgressMonitor monitor) {
				        	 viewer.setInput(resultFeed);
				         }
				      },
				      null
				      //Platform.getWorkspace().getRoot()
				      );
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
		
		Display.getDefault().syncExec(new Runnable() {
			@Override
			public void run() {
				viewer.setInput(resultFeed);
			}			
		});
		//viewer.setInput(resultFeed);
	}
	
	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				GContactsView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(refreshAction);
		manager.add(new Separator());
		manager.add(filterNameAction);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(refreshAction);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(refreshAction);
	}

	private void makeActions() {
		refreshAction = new Action() {
			public void run() {
				
				class UpdateJob extends Job {
				      public UpdateJob() {
				         super("Contacts fetch");
				         setUser(true);
				      }

					@Override
					protected IStatus run(IProgressMonitor monitor) {
						//TODO handle cancel and error 
						connectGContacts();
						return Status.OK_STATUS;
					}				      
				}
				
				if (!net.synck.gcontacts.Activator.getDefault().isGoogleServiceAuthenticated()) {
					UserCredentialsDialog dialog = new UserCredentialsDialog(getSite().getShell());
					
					dialog.setLoginString(
							net.synck.gcontacts.Activator.getDefault().getSecurePreferenceStore()
								.getString(PreferenceConstants.P_ACCOUNTNAME)
					);

					dialog.setPasswordString(
							net.synck.gcontacts.Activator.getDefault().getSecurePreferenceStore()
								.getString(PreferenceConstants.P_ACCOUNTPASSWORD)
					);

												
					if (dialog.open() == Dialog.OK) {
						
						try {
							net.synck.gcontacts.Activator.getDefault()
								.getContactsService().setUserCredentials(dialog.getLoginString(), dialog.getPasswordString());
						} catch (AuthenticationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							return;
						} 	
						net.synck.gcontacts.Activator.getDefault()
							.setGoogleServiceAuthenticated(true);
						
						if (dialog.isSaveCredentials()) {
							net.synck.gcontacts.Activator.getDefault().getSecurePreferenceStore()
							.setValue(PreferenceConstants.P_ACCOUNTPASSWORD, dialog.getPasswordString());							

							net.synck.gcontacts.Activator.getDefault().getSecurePreferenceStore()
							.setValue(PreferenceConstants.P_ACCOUNTNAME, dialog.getLoginString());
							
							try {
								net.synck.gcontacts.Activator.getDefault().getSecurePreferenceStore().save();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								//e.printStackTrace();
							}
						}
						
					} else {
						return;
					}					
	
				}
											
				//connectGContacts();
				IWorkbenchSiteProgressService siteService =
				      (IWorkbenchSiteProgressService)getSite().getAdapter(IWorkbenchSiteProgressService.class);
				   siteService.schedule(new UpdateJob(), 0 /* now */, true /* use the half-busy cursor in the part */);

			}
		};
		refreshAction.setText("Refresh");
		refreshAction.setToolTipText("Refresh contacts");
		refreshAction.setImageDescriptor(
				net.synck.gcontacts.Activator.getImageDescriptor("icons/arrow_refresh.png"));
		
				
		

		
		doubleClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection)selection).getFirstElement();
				//showMessage("Double-click detected on "+obj.toString());
							
				ContactEntry contact = (ContactEntry) obj;
												
				ContactEditorInput input = new ContactEditorInput(contact.getId());
				
				IWorkbenchPage page = PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow().getActivePage();
				try {
					page.openEditor(input, ContactEditor.ID);
					// notify any listeners of the view with the actual data of
					// the view
					viewer.setSelection(viewer.getSelection());
				} catch (PartInitException e) {
					System.out.println(e.getMessage());
				}

			}
		};
		
		filterNameAction = new Action("Show contacts without name", IAction.AS_CHECK_BOX) {
		    public void run() {
		    	if (!this.isChecked()) {
		    		viewer.addFilter(filterNameFilter);
		    	} else {
		    		viewer.removeFilter(filterNameFilter);
		    	}
		    }
		};
		    
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"GContacts View",
			message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}